<?php
class CmsDictionaryModel extends Model
{
    protected $langId;
    protected static $instance;
    protected $e;

    public function CmsDictionaryModel()
    {
        parent::__construct();
        if (RequestHandler::IsExisted('langEdit'))
        {
            try
            {
                AclPermissionModel::Authorize(AppConfig::GetUserModel()->GetCurrentUserId(), 'AdminResource', 'edit');
                $this->SetEditMode(RequestHandler::Get('langEdit'));
            }
            catch (NoPermissionException $ex)
            {
                MessageBase::Warning($ex->getMessage());
            }
        }
    }

    public static function GetInstance()
    {
        return self::$instance ? self::$instance : self::$instance = new CmsDictionaryModel();
    }

    protected function LoadFields()
    {
        parent::LoadFields();
        $this->SetForeignKey('language_id', 'cms_language', 'id');
    }

    public function Translate($content, $langId)
    {
        $this->langId = $langId;
        $this->TranslateElement('title', $content);
        $this->TranslateElement('meta', $content);
        $this->TranslateElement('li', $content);
        $this->TranslateElement('span', $content);
        $this->TranslateElement('a', $content);
        $this->TranslateElement('h1', $content);
        $this->TranslateElement('h2', $content);
        $this->TranslateElement('h3', $content);
        $this->TranslateElement('h4', $content);
        $this->TranslateElement('option', $content);
        $this->TranslateElement('lang', $content);
        if ($this->EditModeEnabled())
            $content .= '<script>new LangEdit();</script>';
        return $content;
    }

    protected function TranslateElement($e, &$content)
    {
        $this->e = $e;
        $regexp = $e == 'lang' ?  "<$e>(.*)<\/$e>" : "<{$e}[^>]*>([^>0-9:]*)<\/{$e}>";
        $content = preg_replace_callback("/$regexp/siU", array($this, 'Callback'), $content);
    }

    public function Callback($match)
    {
        $key = $match[1];
        $value = $this->Lookup($key, $this->langId);
        if ($this->EditModeEnabled() && $this->e != 'option')
            $value = "<span class='langEdit' langKey='$key'>$value</span>";
        return $this->e == 'lang' ? $value : str_replace(">$key<", ">$value<", $match[0]);
    }

    protected function Lookup($key, $langId)
    {
        if (!$key) return $key;
    	$entry = $this->GetEntryValue($key, $langId);
        if (!$entry && AppConfig::GetInstance()->LANGUAGE_SERVICE_MODE)
        {
            $entry = $this->LookupService($key, $langId);
            if ($entry && $entry != $key && (AppConfig::GetInstance()->LANGUAGE_SERVICE_INSERT_MODE || RequestHandler::IsExisted('addLang')))
                $this->AddEntry($key, $langId, $entry);
            else if (!$entry && $langId != AppConfig::GetInstance()->DEFAULT_LANGUAGE)
                $entry = $this->GetEntryValue($key, AppConfig::GetInstance()->DEFAULT_LANGUAGE);
        }
    	return $entry ? $entry : $key;
    }

    public function AddEntry($key, $langId, $entry)
    {
        $item['key'] = $key;
        $item['language_id'] = $langId;
        $item['value'] = $entry;
        return $this->Save($item);
    }

    protected function GetEntryValue($key, $langId)
    {
        $cond = new SqlCondition();
    	$cond->AddString('`key`', $key);
    	$cond->AddString('language_id', $langId);
    	return $this->FindScalar($cond, 'value');
    }

    protected function LookupService($key, $langId)
    {
    	$service = new GoogleTranslate();
        return $service->translate($key, $langId, AppConfig::GetInstance()->DEFAULT_LANGUAGE);
    }

    protected function EditModeEnabled()
    {
        return Session::Get('LangEditMode');
    }

    public function SetEditMode($value)
    {
        return Session::Set('LangEditMode', $value);
    }
}
?>